package com.aigou.admin.controller;

import com.aigou.admin.entity.ResponseEntity;
import com.aigou.admin.util.OSSUtils;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/upload")
public class UploadController extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //创建上传对象
        ServletFileUpload upload = new ServletFileUpload();
        String url = null;
        //判断请求中是否有上传内容
        if(ServletFileUpload.isMultipartContent(req)){
            //设置上传的大小
            upload.setFileSizeMax(10 * 1024 * 1024);
            //获得表单的内容迭代器
            try {
                FileItemIterator itemIterator = upload.getItemIterator(req);
                //遍历表单内容
                if(itemIterator.hasNext()){
                    FileItemStream itemStream = itemIterator.next();
                    //获得文件流，上传到OSS
                    OSSUtils.upload(itemStream.openStream(),itemStream.getName());
                    //获得OSS文件路径
                    url = OSSUtils.getURL(itemStream.getName());
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
        }
        ResponseEntity.ok(resp,url);
    }
}
